package com.example.phone.account.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.phone.Login.LoginActivity;
import com.example.phone.R;
import com.example.phone.account.adapter.AddressRecycleAdapter;
import com.example.phone.base.BaseActivity;
import com.example.phone.base.MyApp;
import com.example.phone.base.RequestInterface;
import com.example.phone.base.ServerResponse;
import com.example.phone.bean.AddressItem;
import com.example.phone.bean.AddressList;
import com.example.phone.bean.Constants;
import com.example.phone.bean.User;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Administrator on 2018\12\26 0026.
 */

public class ManageActivity extends BaseActivity {

    @BindView(R.id.recylerView)
    RecyclerView recylerView;
    @BindView(R.id.tv_add_address)
    TextView tv_add_address;
    @BindView(R.id.iv_go_back)
    ImageView ivGoBack;

    /**
     * 存储后台获取到的地址信息
     */
    AddressList addressList;

    static final int LOGIN_SUCCESS = 1;

    RecyclerView.Adapter adapter;
    /**
     * 用户id
     */
    int userId;
    User user;


    /**
     * 定制的地址信息
     */
    List<AddressItem> addressItems = new ArrayList<>();

    Call<ServerResponse<AddressList>> call;

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case LOGIN_SUCCESS:
                    setAddressItems();

                    if (adapter == null) {

                        adapter = new AddressRecycleAdapter(getContext(), addressItems);
                        log("handler =======  " + addressItems.get(0).getName());

                        recylerView.setAdapter(adapter);
                    } else {
                        adapter.notifyDataSetChanged();
                    }


                    break;
            }

        }
    };



    @Override
    public void initData() {
        log("ManageActivity" + "数据初始哈");

    }

    /**
     * 数据初始化
     */
    private void setAddressItems() {
        List<AddressList.ListBean> list = addressList.getList();
        if (addressItems.size() != 0) {
            addressItems.clear();
        }
        for (int i = 0; i < list.size(); i++) {
            AddressItem addressItem = new AddressItem();

            addressItem.setUserName(user.getUsername().trim());
            addressItem.setShippingId(list.get(i).getId());
            addressItem.setAddress(list.get(i).getAddress().trim());
            addressItem.setCity(list.get(i).getCity().trim());
            addressItem.setName(list.get(i).getName().trim());
            log("addressItem.setName = " + addressItem.getName());
            addressItem.setProvince(list.get(i).getProvince().trim());
            addressItem.setPhone(list.get(i).getMobile().trim());
            addressItems.add(addressItem);

        }


    }

    @Override
    public void initView() {

        //获取userId

        if(user != null){
            userId = user.getId();
            //查询地址列表，完成addressList的赋值
            searchAddressList(userId);
        }

        else {
            Log.d("UserIdManage",""+userId);
            toastShort("未登录");
            goNextActivity(LoginActivity.class);
        }

        ButterKnife.bind(this);

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recylerView.setLayoutManager(layoutManager);

    }


    @Override
    protected void onResume() {
        log("------ManageActivity--------onResume------------");
        super.onResume();
        MyApp myApp = (MyApp) getApplication();
        user = myApp.getUser();
        userId = user.getId();
        searchAddressList(userId);
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }

    }

    @Override
    public int initLayout() {
        MyApp myApp = (MyApp) getApplication();
        user = myApp.getUser();
        return R.layout.manage_activity;
    }

//    @Override
//    protected void onResume() {
//        super.onResume();
//        //重新调用初始化视图查看防止数据更新页面为更新
//        searchAddressList(userId);
//    }

    /**
     * 查询地址列表
     *
     * @param userId 用户id
     */
    public void searchAddressList(int userId) {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(RequestInterface.basePath)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        //实例化ManageAddress类
        RequestInterface.ManageAddress requestInterfaceAddress = retrofit.create(RequestInterface
                .ManageAddress.class);

        call = requestInterfaceAddress
                .getAddrssList(userId);


        call.enqueue(new Callback<ServerResponse<AddressList>>() {
            @Override
            public void onResponse(Call<ServerResponse<AddressList>> call, Response<ServerResponse<AddressList>> response) {
                if (response.body() == null) {
                    toastShort("网络异常，" +
                            "请检查网络配置");

                    return;
                }

                if (response.body().getStatus() == 0) {
                    addressList = response.body().getData();
                    log(addressList.getList().get(0).getName());
                    toastShort("获取地址数据成功！");
                    log("获取地址数据成功！");
                    handler.removeMessages(LOGIN_SUCCESS);
                    handler.sendEmptyMessage(LOGIN_SUCCESS);


                } else {
                    toastShort("获取地址数据失败");
                    log("onRespnse: 获取地址数据失败");
                }

            }

            @Override
            public void onFailure(Call<ServerResponse<AddressList>> call, Throwable t) {
                Log.d(TAG, "onFailure: ");
                toastShort("获取地址数据失败");
                log("onFailure: 获取地址数据失败");
            }
        });


    }


    @OnClick({R.id.tv_add_address, R.id.iv_go_back})
    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.tv_add_address:
                Intent intent = new Intent(this, AddAddressActivity.class);
                intent.putExtra("page", Constants.ADD_ADDRESS);
                startActivity(intent);
                break;

            case R.id.iv_go_back:
                goNextActivity(TestActivity.class);
                finish();
        }


    }




}
